package mspbots.data.tl.prod.autotask.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultEntity;
import mspbots.data.tl.prod.autotask.mapper.TaskAutotaskPhaseMapper;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskPhase;
import mspbots.data.tl.prod.autotask.service.TaskAutotaskPhaseService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Log4j2
@RequiredArgsConstructor
@DS("master")
public class TaskAutotaskPhaseServiceImpl extends AbstractBaseServiceImpl<TaskAutotaskPhaseMapper, TaskAutotaskPhase>
        implements TaskAutotaskPhaseService {

    @Override
    public void sync(ResultEntity content){
        log.debug("Auto task phase receiver content {}", content);
        JsonNode entity = content.getEntity();
        TaskAutotaskPhase data = TaskAutotaskPhase.builder()
                .phaseId(super.getLongValue(entity.get("id")))
                .creatorResourceId(super.getLongValue(entity.get("creatorResourceID")))
                .parentPhaseId(super.getLongValue(entity.get("parentPhaseID")))
                .projectId(super.getLongValue(entity.get("projectID")))
                .externalId(super.getLongValue(entity.get("externalID")))
                .description(super.getStringValue(entity.get("description")))
                .phaseNumber(super.getStringValue(entity.get("phaseNumber")))
                .title(ObjectUtils.isEmpty(entity.get("title"))?null : entity.get("title").asText())
                .isScheduled(super.getBooleanValue(entity.get("isScheduled")))
                .estimatedHours(ObjectUtils.isEmpty(entity.get("estimatedHours"))?null : entity.get("estimatedHours").asDouble())
                .startDate( super.getDateTimeValue(entity.get("startDate")) )
                .createDate(super.getDateTimeValue(entity.get("createDate")))
                .lastActivityDateTime(super.getDateTimeValue(entity.get("lastActivityDateTime")))
                .dueDate(super.getDateTimeValue(entity.get("dueDate")))
                .syncTime(LocalDateTime.now())
                .build();
        data.setTenantCode(content.getTenantId());

        TaskAutotaskPhase dbData = super.baseMapper.selectOne(Wrappers.<TaskAutotaskPhase>lambdaQuery()
                .eq(TaskAutotaskPhase::getTenantCode, data.getTenantCode())
                .eq(TaskAutotaskPhase::getPhaseId, data.getPhaseId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)) {
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }
    }


}
